package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 0. 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1. 判断当前请求是否是登录请求,如果是登录请求直接放心
        String path = request.getURI().getPath();
        if (path.contains("login")){
            // 是登录请求，直接放行
            return chain.filter(exchange);
        }
        // 2. 不是登录请求，获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            // 没有携带token，返回401，不要放行(请求就结束了)
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else {
            // 携带了token，校验token是否合法
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int flag = AppJwtUtil.verifyToken(claims);
            if (flag == 1 || flag == 2){
                // token解析失败，返回401，不要放行(请求就结束了)
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
        // 携带了token，并且token有效，直接放行
        return chain.filter(exchange);
    }

    /**
     * 用于控制过滤器的顺序，值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
